package com.Reporte_Evolutivo;


import java.util.ArrayList;

import java.util.concurrent.ExecutionException;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.BD.BD_RE;

import com.ClasesGraficas.evoGraf;
import com.Generales.login;
import com.JSON.JSONParser_Final;
import com.Reporte_Venta.VentasGenerales;
import com.Tablas.Tabla_Zona;
import com.Generales.R;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;

import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;



public class RE_4_Genera_Reporte extends Activity {
	
	double xInicial[]={0};
	int yInicial[]={0};
	
	private String nombZonaSpinner="";
	/******************************************/
	 private boolean btnDia = false;
	 private boolean btnSemana = false;
	 private boolean btnQuincena = false;
	 private boolean btnMes = false;
	 /*******************************************/	
	private Button btn_gnrReporte= null;
	/***************************************************/
	LinearLayout menuEvolutivo = null;
	private String idEvento;
	LinearLayout layoutGrafica = null;
	GraphicalView mChartView = null;
	private BD_RE db = null;
	TextView valueTextView;
	JSONArray registros = null;
	ArrayList<Registro_Venta> arrayRe = new ArrayList<Registro_Venta>();

	/*******************************************************************/
	String nomEvento;				//1
    String tipoEvento;				//2
    String subtipoevento;			//3
    String fechaRealizacion;		//5
    String MIS_Date;				//6
    String nombreCanal;				//18
    String Monto;					//20
    String Mes;						//21
    String Quincena;
    String Semana;
    String Dia;
    String Zona;
	private String nombreUser;
    /**********************************************************************/
	private ProgressDialog dialog;
	private int idperfil;
	private String idPromotor;
    /******************************************************************/
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		
		nombreUser = this.getIntent().getExtras().getString("nombreUser");
		idEvento= this.getIntent().getExtras().getString("idEvento");
		idperfil = this.getIntent().getExtras().getInt("idperfil");
		idPromotor = this.getIntent().getExtras().getString("idPromotor");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.re_4_genera_reporte);
		
		db = new BD_RE(this);
		
		dialog = new ProgressDialog(this);
    	dialog.setMessage("Descargando las ventas...");
    	dialog.setTitle("Por favor espere");
    	dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    	dialog.setCancelable(false);
    	new progress().execute();
		
		
		//arrayRe = getVentas(idEvento); //se llena el arry con data del json	
		
		for(int i =0; i<arrayRe.size();i++){//se agregan las ventas a la BD
			db.addRegistroVentas(arrayRe.get(i));
		}
		
		Spinner s = (Spinner)findViewById(R.id.spinner);
		ArrayList<Tabla_Zona> zonas = new ArrayList<Tabla_Zona>();
		
		zonas = db.getZonas(idEvento);
		db.close();
		
		final ArrayList<String> nomZonas = new ArrayList<String>();
		nomZonas.add("Todas las Zonas");
		for(int i=1; i<zonas.size()+1 ;i++){
			nomZonas.add(zonas.get(i-1).getNomZona());
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,
				nomZonas);		
		adapter.setDropDownViewResource(
	            android.R.layout.simple_spinner_dropdown_item);
	        s.setAdapter(adapter);
	        s.setOnItemSelectedListener(
	            new AdapterView.OnItemSelectedListener() {
	                public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {	                	
	                	nombZonaSpinner= nomZonas.get(position);
	                	Log.d("nomb Zona", nombZonaSpinner);
	                }
	                public void onNothingSelected(AdapterView<?> parent) {
	                }
	            }
	        );
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
		
		Resources res = getResources();
		Drawable myImage = res.getDrawable(R.drawable.background2);		
		ActionBar actionBar = this.getActionBar();
		actionBar.setBackgroundDrawable(myImage);
		actionBar.setDisplayUseLogoEnabled(true);
		actionBar.setTitle(nombreUser);
		
		//actionBar.setDisplayShowTitleEnabled(false);
		
		
		btn_gnrReporte = (Button) findViewById(R.id.buttonGR);

		btn_gnrReporte.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View v) {
		                generaReporte();
		            }		            
		            
		        });
		nomEvento = getNombreEvento(idEvento);       
		generaGrafico(yInicial, xInicial, "", 5);
	}
	
	private String getNombreEvento(String idEvento2) {
		String nombre = "";
		JSONArray  jArray = null;
		try {
			jArray = (new JSONParser_Final().execute("http://200.16.7.112:3000/reports_management/report/nombreevento/"+idEvento2+".json")).get();
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			
			e.printStackTrace();
		}
		
		try {
			for(int i = 0; i < jArray.length(); i++){
				 JSONObject jsonItem = jArray.getJSONObject(i);
		         JSONObject jsonItem1 = jsonItem.getJSONObject("cubo_evento");
		         
		         nombre = jsonItem1.getString("nomEvento");
		        
			}
		}catch (JSONException e) {
		     e.printStackTrace();
		 }
		return nombre;
	}

	private void muestraPanel()
	{
		LinearLayout ll7 = (LinearLayout)findViewById(R.id.menu_evo);
		
		if (ll7.getVisibility() == View.VISIBLE)
			ll7.setVisibility(View.GONE);
		else if(ll7.getVisibility() == View.GONE)
			ll7.setVisibility(View.VISIBLE);
	}
	/*	
	private ArrayList<Registro_Venta> getVentas(String idEvento) {
		ArrayList<Registro_Venta> array = new ArrayList<Registro_Venta>();
		JSONArray  jArray = null;
		try {
			jArray = (new JSONParser_Final().execute("http://200.16.7.112:3000/reports_management/report/evolutivo/"+idEvento+".json")).get();
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			
			e.printStackTrace();
		}
		
		try {
			for(int i = 0; i < jArray.length(); i++){
				 JSONObject jsonItem = jArray.getJSONObject(i);
		         JSONObject jsonItem1 = jsonItem.getJSONObject("fact_venta");
		         
		         int Anho = jsonItem1.getInt("Anho");
		         int Dia = jsonItem1.getInt("Dia");
		         int  Mes= jsonItem1.getInt("Mes");
		         float Monto  = jsonItem1.getInt("Monto");
		         String NombreMes = jsonItem1.getString("NombreMes");
		         int Semana = jsonItem1.getInt("Semana");
		         String nomZona = jsonItem1.getString("nomZona");
		         int quincena = jsonItem1.getInt("quincena");		         
		         
		         Registro_Venta re = new Registro_Venta(Anho, Dia, Mes, Monto, NombreMes, Semana, nomZona, quincena);
		         array.add(re);
			}
		}catch (JSONException e) {
		     e.printStackTrace();
		 }
		return array;
	}
	*/
	public void generaReporte() {
		//PERIODO
		ocultaMenu();
		generaReporte_1(nombZonaSpinner, btnDia, btnSemana, btnQuincena, btnMes);
				
	}
	
	private void generaReporte_1(String nombZonaSpinner2, boolean btnDia2,
			boolean btnSemana2, boolean btnQuincena2, boolean btnMes2) {
		
		if (btnDia2) {
			generaReporte_1_dia(idEvento);
		}
		if (btnSemana2) {
			generaReporte_1_semana(idEvento);
		}
		if (btnQuincena2) {
			generaReporte_1_quincena(idEvento);
		}
		if (btnMes2) {
			generaReporte_1_mes(idEvento);
		}
	}

	private void generaReporte_1_mes(String idEvento2) {

		BD_RE db = new BD_RE(this);
		int[] x = null;
		double[] y = null;
		
		ArrayList<Ventas> montos = new ArrayList<Ventas>();
		
		if (nombZonaSpinner.equals("Todas las Zonas")){
			montos = db.getVentasXMes();
		}else{
			montos = db.getVentasXMesxzONA(nombZonaSpinner);
		}
		
		x = new int [montos.size()];
		y = new double [montos.size()];
		for (int i=0; i<montos.size();i++){
			x[i]=i+1;
			if (i==0){
				y[i]=montos.get(i).getMontos();
			}else{
				y[i]=montos.get(i).getMontos()+y[i-1];	
			}
							
		}
		generaGrafico(x, y, "Ventas Mensuales de: "+nomEvento, 4);
		
		db.close();
	}

	
	private void generaReporte_1_quincena(String idEvento2) {

		BD_RE db = new BD_RE(this);
		int[] x = null;
		double[] y = null;
		
		ArrayList<Ventas> montos = new ArrayList<Ventas>();
		
		if (nombZonaSpinner.equals("Todas las Zonas")){
			montos = db.getVentasXQuincena();
		}else{
			montos = db.getVentasXQuincenaxzONA(nombZonaSpinner);
		}
		
		x = new int [montos.size()];
		y = new double [montos.size()];
		for (int i=0; i<montos.size();i++){
			x[i]=i+1;
			if (i==0){
				y[i]=montos.get(i).getMontos();
			}else{
				y[i]=montos.get(i).getMontos()+y[i-1];	
			}
							
		}
		generaGrafico(x, y, "Ventas Quincenales de: "+nomEvento, 3);
		
		db.close();
		
	}
	
	private void generaReporte_1_semana(String idEvento2) {

		BD_RE db = new BD_RE(this);
		int[] x = null;
		double[] y = null;
		
		ArrayList<Ventas> montos = new ArrayList<Ventas>();
		
		if (nombZonaSpinner.equals("Todas las Zonas")){
			montos = db.getVentasXSemana();
		}else{
			montos = db.getVentasXSemanaXZona(nombZonaSpinner);
		}
		
		
		x = new int [montos.size()];
		y = new double [montos.size()];
		for (int i=0; i<montos.size();i++){
			x[i]=i+1;
			if (i==0){
				y[i]=montos.get(i).getMontos();
			}else{
				y[i]=montos.get(i).getMontos()+y[i-1];	
			}
							
		}
		generaGrafico(x, y, "Ventas Semanales de: "+nomEvento, 2);
		
		db.close();
	}

	private void generaReporte_1_dia(String idEvento2) {

		BD_RE db = new BD_RE(this);
		int[] x = null;
		double[] y = null;
		
		ArrayList<Ventas> montos = new ArrayList<Ventas>();
		
		if (nombZonaSpinner.equals("Todas las Zonas")){
			montos = db.getVentasXDia();
		}else{
			montos = db.getVentasXDiaXZona(nombZonaSpinner);
		}
		
		montos = db.getVentasXDia();
		x = new int [montos.size()];
		y = new double [montos.size()];
		for (int i=0; i<montos.size();i++){
			x[i]=i+1;
			if (i==0){
				y[i]=montos.get(i).getMontos();
			}else{
				y[i]=montos.get(i).getMontos()+y[i-1];	
			}
							
		}
		generaGrafico(x, y, "Ventas Diarias de: "+nomEvento, 1);
		
		db.close();
	}

	private void generaGrafico(int[] x, double[] y, String titulo, int n) {
	
		evoGraf eg = new evoGraf();
		eg.ejecutar(x, y, titulo, n);
		this.layoutGrafica = (LinearLayout)findViewById(R.id.evoGraf);
		
		this.mChartView = ChartFactory.getLineChartView(this,eg.getDataset(), 
				eg.getmRenderer());
		layoutGrafica.removeAllViews();
	    layoutGrafica.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
		               LayoutParams.FILL_PARENT));
	}
		
	public void ocultaMenu(){

		LinearLayout ll7 = (LinearLayout)findViewById(R.id.menu_evo);
		ll7.setVisibility(View.GONE);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        inflater.inflate(R.menu.menuprincipal, menu);
        
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.logout:
	        	Intent logo = new Intent(this,login.class);
	        	startActivity(logo);
	            return true;
	        
	        case android.R.id.home:
	        	muestraPanel();
	            return true;
	        case R.id.menuPrincipal:
	        	Intent menu = new Intent(this,com.Generales.Menu.class);
	        		        	
	        	menu.putExtra("codigo","");
	        	menu.putExtra("nombreUser",nombreUser);
	        	menu.putExtra("idPromotor",idPromotor);
	        	menu.putExtra("idperfil", idperfil);
	        	startActivity(menu);
	            return true; 
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}	
	public void muestraMenu(){
		
		//MENU LATERAL
		LinearLayout ll7 = (LinearLayout)findViewById(R.id.menu_evo);
		ll7.setVisibility(View.VISIBLE);
		
		
	}
	
public void establecerColorTiempo2(View view){		
		
		Button buttonDia = (Button) findViewById(R.id.ButtonDia);
		Button buttonSemana = (Button) findViewById(R.id.ButtonSemana);
		Button buttonQuincena = (Button) findViewById(R.id.ButtonQuincena);
		Button buttonMes = (Button) findViewById(R.id.buttonMes);
	
		if (buttonDia.isPressed()){
			
			btnDia = true;
			btnSemana = false;
			btnQuincena = false;
			btnMes = false;
			
			Drawable d1 = buttonDia.getBackground();
            PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            d1.setColorFilter(filter);
			
			
			Drawable d2 = buttonSemana.getBackground();
            findViewById(R.id.ButtonSemana).invalidateDrawable(d2);
            d2.clearColorFilter();
			
            Drawable d3 = buttonQuincena.getBackground();
            findViewById(R.id.ButtonQuincena).invalidateDrawable(d3);
            d3.clearColorFilter();
            
            Drawable d4 = buttonMes.getBackground();
            findViewById(R.id.buttonMes).invalidateDrawable(d4);
            d4.clearColorFilter();
            
				
			
		}
		if (buttonSemana.isPressed()){
			
			btnDia = false;
			btnSemana = true;
			btnQuincena = false;
			btnMes = false;
			
			Drawable d1 = buttonSemana.getBackground();
            PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            d1.setColorFilter(filter);

			
			Drawable d2 = buttonDia.getBackground();
            findViewById(R.id.ButtonDia).invalidateDrawable(d2);
            d2.clearColorFilter();
			
            Drawable d3 = buttonQuincena.getBackground();
            findViewById(R.id.ButtonQuincena).invalidateDrawable(d3);
            d3.clearColorFilter();
            
            Drawable d4 = buttonMes.getBackground();
            findViewById(R.id.buttonMes).invalidateDrawable(d4);
            d4.clearColorFilter();
            
					
		}
		if (buttonQuincena.isPressed()) {
			
			btnDia = false;
			btnSemana = false;
			btnQuincena = true;
			btnMes = false;
			
			Drawable d1 = buttonQuincena.getBackground();
            PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            d1.setColorFilter(filter);

			
            Drawable d2 = buttonDia.getBackground();
            findViewById(R.id.ButtonDia).invalidateDrawable(d2);
            d2.clearColorFilter();
			
            Drawable d3 = buttonSemana.getBackground();
            findViewById(R.id.ButtonSemana).invalidateDrawable(d3);
            d3.clearColorFilter();
            
            Drawable d4 = buttonMes.getBackground();
            findViewById(R.id.buttonMes).invalidateDrawable(d4);
            d4.clearColorFilter();
            
		}
        if (buttonMes.isPressed()) {
    			
        	btnDia = false;
			btnSemana = false;
			btnQuincena = false;
			btnMes = true;
        	
        	Drawable d1 = buttonMes.getBackground();
            PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            d1.setColorFilter(filter);
    			
            Drawable d2 = buttonDia.getBackground();
            findViewById(R.id.ButtonDia).invalidateDrawable(d2);
            d2.clearColorFilter();
    			
            Drawable d3 = buttonSemana.getBackground();
            findViewById(R.id.ButtonSemana).invalidateDrawable(d3);
            d3.clearColorFilter();
                
            Drawable d4 = buttonQuincena.getBackground();
            findViewById(R.id.ButtonQuincena).invalidateDrawable(d4);
            d4.clearColorFilter();    
						
		}
        
	}

	

	public class progress extends AsyncTask<Void, Void, Void> {
		
		@Override
	    protected void onPreExecute() {
			dialog.setProgress(0);
			dialog.setMax(100);
			dialog.show(); //Mostramos el diálogo antes de comenzar
	    }
		
		@Override
		protected Void doInBackground(Void... params) {
			JSONArray  jArray = null;
			try {
				jArray = (new JSONParser_Final().execute("http://200.16.7.112:3000/reports_management/report/evolutivo/"+idEvento+".json")).get();
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			} catch (ExecutionException e) {
				
				e.printStackTrace();
			}
			
			try {
				for(int i = 0; i < jArray.length(); i++){
					 JSONObject jsonItem = jArray.getJSONObject(i);
			         JSONObject jsonItem1 = jsonItem.getJSONObject("fact_venta");
			         
			         int Anho = jsonItem1.getInt("Anho");
			         int Dia = jsonItem1.getInt("Dia");
			         int  Mes= jsonItem1.getInt("Mes");
			         float Monto  = jsonItem1.getInt("Monto");
			         String NombreMes = jsonItem1.getString("NombreMes");
			         int Semana = jsonItem1.getInt("Semana");
			         String nomZona = jsonItem1.getString("nomZona");
			         int quincena = jsonItem1.getInt("quincena");		         
			         
			         Registro_Venta re = new Registro_Venta(Anho, Dia, Mes, Monto, NombreMes, Semana, nomZona, quincena);
			         arrayRe.add(re);
			         dialog.setProgress((i+1)*100/jArray.length());
				}
			}catch (JSONException e) {
			     e.printStackTrace();
			 }
					
        				
			return null;
			
			
		}
		
	    @Override
	    protected void onPostExecute(Void result) {
	    	dialog.dismiss();

		}
		
	}
}
